<template>
  <div class="register">
    <el-form :model="user" ref="form" label-width="80px" :rules="rules">
      <el-form-item prop="userName" label="用户名">
        <el-input v-model="user.userName"></el-input>
      </el-form-item>
      <el-form-item prop="password" label="密码">
        <el-input v-model="user.password" type="password"></el-input>
      </el-form-item>
      <el-form-item prop="checkPassword" label="确认密码">
        <el-input v-model="user.checkPassword" type="password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="register('form')" style="margin-left: 37%;">提交</el-button>
        <router-link :to="'/dm/login'" class="link">登陆</router-link>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  import {userService} from '../../service/userService'
  import {Msg} from '../../tools/message'

  export default {
    name: 'register',
    data () {
      var validatePass = (rule, value, callback) => {
        if (!value) {
          callback(new Error('请输入密码'))
        } else {
          if (this.checkPassword !== '') {
            this.$refs.form.validateField('checkPassword')
          }
          callback()
        }
      }
      var validatePass2 = (rule, value, callback) => {
        if (!value) {
          callback(new Error('请再次输入密码'))
        } else if (value !== this.user.password) {
          callback(new Error('两次输入密码不一致!'))
        } else {
          callback()
        }
      }
      return {
        user: {},
        checkPassword: '',
        rules: {
          userName: [
            {required: true, message: '请输入用户名', trigger: 'blur'}
            // {required: true, validator: validateUserName, trigger: 'blur'}
          ],
          password: [
            {required: true, validator: validatePass, trigger: 'blur'},
            {min: 6, max: 8, message: '长度在6到8个字符', trigger: 'blur'}
          ],
          checkPassword: [
            {required: true, validator: validatePass2, trigger: 'blur'}
          ],
        }
      }
    },
    methods: {
      register (formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            userService.register(this.user).then(res => {
              if (res.data.status) {
                Msg.success(res.data.msg)
                this.$router.back()
              } else {
                Msg.error(res.data.msg)
              }
            }).catch(error => {
              console.log(error)
            })
          } else {
            console.log('error register')
          }
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
  .link {
    color: #409EFF;
    text-decoration: none;
    float: right;
    padding-top: 3%;
  }
</style>
